package chat

import (
	"context"
	"fmt"
	pitaya "github.com/topfreegames/pitaya/v3/pkg"
	"github.com/topfreegames/pitaya/v3/pkg/component"
	"github.com/topfreegames/pitaya/v3/pkg/logger"
	"server/constants"
	"server/pb/pb_chat"
)

type Remote struct {
	component.Base
}

func (r *Remote) Init() {
	logger.Log.Info("chat remote 启动成功")
}

func NewRemote() *Remote {
	return &Remote{}
}

// RemovePlayerFromChatGroup 离开聊天group
func (r *Remote) RemovePlayerFromChatGroup(ctx context.Context, uid string) {
	//打印一下人数
	membersCount1, _ := pitaya.GroupMembers(ctx, constants.WoldGroup)
	logger.Log.Infof("离开前,[%s group]人数：%d", constants.WoldGroup, len(membersCount1))
	_ = pitaya.GroupRemoveMember(ctx, constants.WoldGroup, uid)
	//打印一下人数
	membersCount2, _ := pitaya.GroupMembers(ctx, constants.WoldGroup)
	logger.Log.Infof("离开后,[%s group]人数：%d", constants.WoldGroup, len(membersCount2))
}

// JoinPlayerToChatGroup 加入聊天group
func (r *Remote) JoinPlayerToChatGroup(ctx context.Context, uid string) {
	membersCount1, _ := pitaya.GroupMembers(ctx, constants.WoldGroup)
	logger.Log.Infof("加入前，group[%s]人数：%d", constants.WoldGroup, len(membersCount1))
	//加入聊天室
	if isContain, err := pitaya.GroupContainsMember(ctx, constants.WoldGroup, uid); isContain {
		logger.Log.Error(err)
		logger.Log.Infof("加入group错误,[%s group]玩家已存在：%s", constants.WoldGroup, uid)
	} else {
		_ = pitaya.GroupAddMember(ctx, constants.WoldGroup, uid)
		membersCount2, _ := pitaya.GroupMembers(ctx, constants.WoldGroup)
		logger.Log.Infof("加入后，[%s group]人数：%d", constants.WoldGroup, len(membersCount2))
	}
}

// RemoteFunc is a function that will be called remotely
func (r *Remote) UserStatusChange(ctx context.Context, msg *pb_chat.UserChatStatus) (*pb_chat.UserChatReply, error) {
	fmt.Printf("received a remote call with this message: %s\n", msg)
	if msg.Status == 1 {
		r.JoinPlayerToChatGroup(ctx, msg.UID)
	} else {
		r.RemovePlayerFromChatGroup(ctx, msg.UID)
	}
	return &pb_chat.UserChatReply{
		OK: fmt.Sprintf("received msg: %s", msg.GetUID()),
	}, nil
}
